//
//  Position.m
//  CarTown
//
//  Created by xionghao on 15/9/8.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "Position.h"
#import <MJExtension.h>
#import "AppDelegate.h"
@implementation Position

@dynamic name;
@dynamic time;
+(void)addPostion:(NSArray *)data{
    AppDelegate *delegate=[[UIApplication sharedApplication]delegate];
    NSFetchRequest *request=[NSFetchRequest fetchRequestWithEntityName:@"Position"];
    NSArray *sets= [delegate.managedObjectContext executeFetchRequest:request error:nil];
    if (sets.count>0) {
      Position *postion= sets[0];
     NSTimeInterval secondsInterval= [postion.time timeIntervalSinceDate:[NSDate date]];
        if ([postion.time isYesterday]||secondsInterval>24*60*60) {
            for (Position *p in sets) {
                [delegate.managedObjectContext deleteObject:p];
            }
            
            for (NSDictionary *dict in data) {
                Position *postion=[NSEntityDescription insertNewObjectForEntityForName:@"Position" inManagedObjectContext:delegate.managedObjectContext];
                [postion setValue:dict[@"name"] forKey:@"name"];
                [postion setValue:[NSDate date] forKey:@"time"];
                [delegate saveContext];
            }
            
        }
        
    }else{
        for (NSDictionary *dict in data) {
            Position *postion=[NSEntityDescription insertNewObjectForEntityForName:@"Position" inManagedObjectContext:delegate.managedObjectContext];
            [postion setValue:dict[@"name"] forKey:@"name"];
            [postion setValue:[NSDate date] forKey:@"time"];
            [delegate saveContext];
        }

    }
    
}

+(NSArray *)getPostion{
    AppDelegate *delegate=[[UIApplication sharedApplication]delegate];
    NSFetchRequest *request=[NSFetchRequest fetchRequestWithEntityName:@"Position"];
    NSSortDescriptor *sort=[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
    request.sortDescriptors=@[sort];
    NSArray *sets= [delegate.managedObjectContext executeFetchRequest:request error:nil];
    return sets;
}

@end
